package com.etcn.common.schedule;

import java.util.Date;
import java.util.Iterator;
import java.util.Set;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.etcn.common.redis.RedisService;

import ch.qos.logback.classic.Logger;

/**
 * 接口统计分析
 * 
 * @author guozc
 */
@Component
public class AnalyzeLogSchedule {
	private Logger log = (Logger) LoggerFactory.getLogger("service_file_log");

	@Autowired
	@Qualifier("busiJdbcTemplate")
	private JdbcTemplate jdbcTemplate;
	
	@Autowired
	private RedisService redisService;

	@Scheduled(cron = "* 0/30 * * * ?")
	public void fetch() throws Exception {
		log.info("---------------------------开始进行api接口统计---------------------------");
		String sql = null;
		// 总访问次数
		Set<ZSetOperations.TypedTuple<Object>> tuples = redisService.reverseRangeWithScore("apicount", 0, -1);
    	Iterator<ZSetOperations.TypedTuple<Object>> iterator = tuples.iterator();
        while (iterator.hasNext())
        {
            ZSetOperations.TypedTuple<Object> typedTuple = iterator.next();
            String[] req = ((String)typedTuple.getValue()).split("\\|");
            String url = req[0];
            String analyzeId = req[1];
            sql = "select count(1) from wm_api_analyze where id = " + analyzeId;
            if(jdbcTemplate.queryForObject(sql, Integer.class) > 0){
            	 sql = "update wm_api_analyze set total_times = ?,analyze_time=? where id = ?";
            	 jdbcTemplate.update(sql, new Object[]{typedTuple.getScore(),new Date(),analyzeId});
            }else{
            	sql = "insert into wm_api_analyze(id,analyze_time,req_url,total_times) values(?,?,?,?)";
                jdbcTemplate.update(sql, new Object[]{analyzeId,new Date(),url,typedTuple.getScore()});
            }
        }
        
        // 错误次数
        tuples = redisService.reverseRangeWithScore("apierror", 0, -1);
    	iterator = tuples.iterator();
        while (iterator.hasNext())
        {
            ZSetOperations.TypedTuple<Object> typedTuple = iterator.next();
            sql = "update wm_api_analyze set fail_times = ?,analyze_time=? where id = ?";
            String[] req = ((String)typedTuple.getValue()).split("\\|");
            String analyzeId = req[1];
            jdbcTemplate.update(sql, new Object[]{typedTuple.getScore(),new Date(),analyzeId});
        }
        System.out.println("over");
	}

}
